<?
/*
 * Galeri, version 0.1
 * (c) 2007 Fajran Iman Rusadi.
 *
 * Galeri is freely distributable under the terms of an MIT-style license.
 *
 */

include('config.php');
include('common.php');

$action = isset($_POST['s']) ? trim(strtolower($_POST['s'])) : '';

if ($action == 'init') {

	print('{ status: "ok", data: { ');
	print(' name: "' . addslashes($_name) . '" ');
	print(' } } ');

}
else if ($action == 'showdirectory') {

	$path = isset($_POST['dir']) ? $_POST['dir'] : '';
	$page = isset($_POST['page']) ? intval($_POST['page']) : 0;
	$index = isset($_POST['index']) ? intval($_POST['index']) : 0;
	$pageSize = 20;

	$dirs = array();
	$images = array();

	$pathinfo = getValidPath($path);
	if ($pathinfo !== false) {
		
		$base = $pathinfo['base'];
		$path = $pathinfo['path'];
		
		if ($dir = opendir($base . $path)) {
			//read directory
			while (false !== ($d = readdir($dir))) {
				$fullpath = $base . $path . '/' . $d;
			    
				//skip ., .., and hidden directory
				if (($d == '.') || ($d == '..') || (substr($d, 0, 1) == '.') || isTitleText($fullpath)) { 
					continue; 
				}

				//check if directory
				if (is_dir($fullpath)) {
					$dirs[] = array($d, $path . '/' . $d);
				}

				//check if image
				else if (getimagesize($fullpath)) {
					$images[] = $d;
				}
			}
		}

		sort($images);
		$totalPages = ceil(count($images) / $pageSize);
		$images = array_slice($images, $page * $pageSize, $pageSize);
	
		print('{ status: "ok", data: { ');
		print(' dir: "' . $path . '", ');
		print(' images: [ ');
		foreach ($images as $img) {
			$url = addslashes('image.php' . $path . '/' . $img);
			$thumbUrl = addslashes('thumbnail.php' . $path . '/' . $img);
	
			print('{ url: "' . $url . '", thumbUrl: "' . $thumbUrl . '", caption: "<div id=\'imgTitle\'>' . readCaptionImage($base . $path . '/' . $img) . '</div><div id=\'imgDetail\'>' . readDetailImage($base . $path . '/' . $img) . '</div>"}, ');
		}
		print(' ], subdirs: [ ');
		foreach ($dirs as $dir) {
			print(' { path: "' . addslashes($dir[1]) . '", label: "' . addslashes($dir[0]) . '"}, ');
		}
		print(' ], page: [ ' . $page . ', ' . $totalPages . ' ], ');
		print(' index: ' . $index);
		print(' } } ');
	}
	else {
		print('{ status: "error", data: { error: "Invalid path." } }');
	}
}

?>
